package com.yuchen.ishop.web.app.seller;

import com.yuchen.core.MyPager;
import com.yuchen.ishop.Gobals;
import com.yuchen.ishop.entity.Seller;
import com.yuchen.ishop.entity.SellerXiaoer;
import com.yuchen.ishop.service.CacheService;
import com.yuchen.ishop.service.file.FileRequest;
import com.yuchen.ishop.service.file.FileRestClient;
import com.yuchen.ishop.service.goods.GoodsHouseRestClient;
import com.yuchen.ishop.service.seller.XiaoerRestClient;
import com.yuchen.ishop.vo.CookieUserInfo;
import com.yuchen.ishop.vo.FileResponse;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.jaxrs.Responses;
import com.yuchen.utils.security.PasswordUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的店小二
 */
@Controller
@RequestMapping(value = "/my/seller")
public class XiaoerAction extends BaseAction {

    private final static Logger LOG = Logger.getLogger(XiaoerAction.class);

    @Autowired
    private XiaoerRestClient xiaoerRestClient;

    @Autowired
    private FileRestClient fileRestClient;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private GoodsHouseRestClient goodsHouseRestClient;


    @RequestMapping(value = "myXiaoer")
    public String myXiaoer(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        modelMap.addAttribute("myMenu", "myXiaoer");
        Map params = convertParameterMap(request.getParameterMap());
        CookieUserInfo userInfo = cookie2UserInfo(request);
        if (params == null) params = new HashMap();
        params.put("sellerId", userInfo.getId());
        MyPager myPager = xiaoerRestClient.findXiaoers(params);
        modelMap.addAttribute("pager", myPager);
        return "my/seller/myXiaoer";
    }

    @RequestMapping(value = {"/addXiaoer", "/editXiaoer"})
    public String add_edit_xiaoer(Long id, ModelMap modelMap) throws Exception {
        modelMap.addAttribute("sysGoodsType", cacheService.getDictionaryCache());
        modelMap.addAttribute("myMenu", "myXiaoer");
        if (null == id)
            return "my/seller/addXiaoer";
        else {
            modelMap.addAttribute("xiaoer", xiaoerRestClient.getXiaoer(id));
            return "my/seller/editXiaoer";
        }
    }

    @RequestMapping(value = "/saveXiaoer", method = RequestMethod.POST)
    public String saveXiaoer(SellerXiaoer xiaoer, Long pageNo, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
        String photo  = uploadPhoto(xiaoer.getPhoto(),request);
        pageNo = pageNo == null ? 1l : pageNo;
        xiaoer.setState(1l);
        Map map = PasswordUtils.genMD5Str(xiaoer.getPassword());
        xiaoer.setPassword((String) map.get("password"));
        xiaoer.setSalt((String) map.get("salt"));
        xiaoer.setPhoto(photo);
        xiaoer.setCreateTime(getTime());
        xiaoerRestClient.insertXiaoer(xiaoer);

        return "redirect:/my/seller/myXiaoer.htm?pageNo=" + pageNo;
    }

    @RequestMapping(value = "/updateXiaoer", method = RequestMethod.POST)
    public String updateXiaoer(SellerXiaoer xiaoer, Long pageNo, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
        String photo  = uploadPhoto(xiaoer.getPhoto(),request);
        if(StringUtils.isNotBlank(photo)){
            xiaoer.setPassword(photo);
        }
        pageNo = pageNo == null ? 1l : pageNo;
        if (StringUtils.isNotBlank(xiaoer.getPassword())) {
            Map map = PasswordUtils.genMD5Str(xiaoer.getPassword());
            xiaoer.setPassword((String) map.get("password"));
            xiaoer.setSalt((String) map.get("salt"));
        }
        //xiaoer.setCreateTime(getTime());
        xiaoerRestClient.updateXiaoer(xiaoer);
        return "redirect:/my/seller/myXiaoer.htm?pageNo=" + pageNo;
    }

    @RequestMapping(value = "/deleteXiaoer", method = RequestMethod.GET)
    public String deleteXiaoer(Long id, Long pageNo, RedirectAttributes redirectAttributes) throws Exception {
        pageNo = pageNo == null ? 1l : pageNo;
        Responses responses = xiaoerRestClient.deleteXiaoer(id);
        return "redirect:/my/seller/myXiaoer.htm?pageNo=" + pageNo;
    }


    @RequestMapping(value = "/xiaoerInfo")
    public String xiaoerInfo(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        CookieUserInfo userInfo = cookie2UserInfo(request);
        if("xiaoer".equals(userInfo.getRole())){
            modelMap.addAttribute("myMenu", "userInfo");
            SellerXiaoer xiaoer = xiaoerRestClient.getXiaoer(userInfo.getId());
            xiaoer.setPassword(null);
            xiaoer.setSalt(null);
            modelMap.put("xiaoer",xiaoer);
            return "/my/seller/xiaoerInfo";
        }
        return "redirect:/error.htm";
    }

    @RequestMapping(value = "/saveOrUpdateXiaoer", method = RequestMethod.POST)
    public String saveOrUpdateXiaoer(SellerXiaoer xiaoer, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
        if(xiaoer.getId()!=null){
            String photo = uploadPhoto(xiaoer.getPhoto(),request);
            if(StringUtils.isNotBlank(photo)){
                xiaoer.setPassword(photo);
            }
            xiaoerRestClient.updateXiaoer(xiaoer);
            redirectAttributes.addFlashAttribute(Gobals.MSG,successJson());
            return "redirect:/my/seller/xiaoerInfo.htm";
        }
        return "redirect:/error.htm";
    }

    @RequestMapping(value = "xiaoerPwd")
    public String xiaoerPwd(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        CookieUserInfo userInfo = cookie2UserInfo(request);
        if("xiaoer".equals(userInfo.getRole())){
            modelMap.addAttribute("myMenu", "password");
            SellerXiaoer xiaoer= xiaoerRestClient.getXiaoer(userInfo.getId());
            modelMap.put("xiaoerId",xiaoer.getId());
            return "/my/seller/xiaoerPwd";
        }
        return "redirect:/error.htm";
    }


    @RequestMapping(value = "updateXiaoerPwd",method = RequestMethod.POST)
    public String updateSellerPwd(Long id,String password, HttpServletRequest request,RedirectAttributes redirectAttributes) {
        if(id!=null && StringUtils.isNotBlank(password)){
            Map map = new HashMap(2);
            map.put("id",id);
            map.put("password",password);
            xiaoerRestClient.updatePwd(map);
            redirectAttributes.addFlashAttribute(Gobals.MSG,successJson());
            return "redirect:/my/seller/xiaoerPwd.htm";
        }
        return "redirect:/error.htm";
    }

    @RequestMapping(value = "xiaoqu")
    @ResponseBody
    public List xiaoqu(String keyword, HttpServletRequest request,RedirectAttributes redirectAttributes) {
        List arr  = new ArrayList();
        List list = goodsHouseRestClient.findXiaoqu(keyword);
        if(list !=null && list.size()>0){
            Map m = null;
            for(int i=0;i<list.size();i++){
                m = (Map) list.get(i);
                arr.add(m.get("community_name"));
            }
        }
        return arr;
    }


    private String uploadPhoto(String oldPhotoUrl, HttpServletRequest request){
        String photo = "";
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("file");
            if (null != files && files.size() > 0) {
                for (MultipartFile file : files) {
                    String type = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
                    FileRequest req = new FileRequest(type, "xiaoer", file.getInputStream());
                    FileResponse response = fileRestClient.sendFile(req);
                    if (response.getStatus()) {
                        photo = response.getPath();
                    }
                }
            }
            if(StringUtils.isNotBlank(photo) && StringUtils.isNotBlank(oldPhotoUrl)){
                fileRestClient.deleteFile(oldPhotoUrl);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

        return photo;
    }


}
